<?php

if (!defined('IN_XLP')) {
    exit('Access Denied');
}

/**
 * Description of feiyin
 * 飞印打印接口类
 * @author xlp
 */
class feiyinApi {

    static private $apiUrl = 'http://my.feyin.net/api/sendMsg';
    static private $orderData = null;
    static private $setting = array();

    /*
     * 初始化连接设置
     */

    static public function init($setData) {
        self::$setting = array(
            'apiKey' => $setData['api_key'], //FEYIN_KEY
            'mKey' => $setData['m_key'], //MEMBER_CODE
            'partner' => $setData['partner_id'],
            'machine_code' => $setData['machine_code'], //DEVICE_NO
        );
    }

    /*
     * 发送数据
     */

    static public function send($data) {
        self::$orderData = &$data['info']; //设置订单数据
        $res = array();
        $homeData = array();
        $i = 1;
        foreach ($data['order'] as $key => $val) {
            self::init($val['print']);
            $params = array(
                'deviceNo' => self::$setting['machine_code'],
                'memberCode' => self::$setting['mKey'],
                'msgDetail' => self::printDetailData($val, $i, true, 0),
//                'msgNo' => TIME . $key . mt_rand(100, 999),
                'reqTime' => TIME * 1000,
                'mode' => 2
            );
            $params['securityCode'] = self::generateSign($params);
            $res[$key] = array(
                'name' => $val['shop_name'],
                'result' => self::getResultMsg(getHttp(self::$apiUrl, $params))
            );
            //打印出货单
            $homeData[] = array(
                'items' => $val['items'],
                'shop_name' => $val['shop_name'],
            );
            $i+=1;
        }
//        echo "\n\n\n";
        self::init($data['print']);
        $params = array(
            'deviceNo' => self::$setting['machine_code'],
            'memberCode' => self::$setting['mKey'],
//            'msgNo' => TIME . $key . mt_rand(100, 999),
            'reqTime' => TIME * 1000,
            'mode' => 2
        );
        $params['msgDetail'] = self::printDetailData($homeData, 0, false, 1);
        $params['securityCode'] = self::generateSign($params);
        $res['home1'] = array(
            'name' => '客户联',
            'result' => self::getResultMsg(getHttp(self::$apiUrl, $params))
        );
//        $params['msgNo'] = TIME . ($key+1) . mt_rand(100, 999);
        $params['reqTime'] = TIME * 1000;
        $params['msgDetail'] = self::printDetailData($homeData, 0, false, 2);
        $params['securityCode'] = self::generateSign($params);
        $res['home2'] = array(
            'name' => '出货联',
            'result' => self::getResultMsg(getHttp(self::$apiUrl, $params))
        );
        return $res;
    }

    static public function printDetailData($data, $key = 0, $isShop = true, $bill = 0) {
        switch ($bill) {
            case 1:$billName = '客户联';
                break;
            case 2:$billName = '出货联
编号:' . self::$orderData['order_no'];
                break;
            default :$billName = '';
        }
        $message = '           结邻公社
订单号:' . self::$orderData['order_sn'];
        if ($isShop) {
            $message .='
联单:' . $key . '/' . self::$orderData['printCounts'] . '
商户:' . $data['shop_name'];
        } else {
            $message .='
联单:' . $billName;
        }
        $message .='

条目          单价(元)      数量
--------------------------------
';
//获得格式化打印字符串
        if ($isShop) {
            $message .=self::getDetailList($data);
        } else {
            foreach ($data as $v) {
                $message .=self::getDetailList($v, $v['shop_name']);
            }
        }
        $message .='--------------------------------
'; // && $bill == 2
        $message .=(self::$orderData['desc']) ? '备注:' . self::$orderData['desc'] . '
' : '';
        if ($isShop) {
            $message .= '合计:' . $data['order_amount'] . '元
';
        } else {
            $message .= '折减:' . self::$orderData['offset'] . '元 运费:' . self::$orderData['shipping_fee'] . '元
合计:' . self::$orderData['order_amount'] . '元

送货地址:' . self::$orderData['address'] . '
联系人:' . self::$orderData['username'] . '
联系电话:' . self::$orderData['phone'];
        }
        $message .= '
下单时间:' . self::$orderData['order_time'] . '
配送时间:' . self::$orderData['arrive_date'] . ' ' . self::$orderData['arrive_time'];
        if ($bill == 2) {
            $message .= '
客户签字:';
        }
//        echo $message, "\n\n\n\n";
//        exit;
        return $message;
    }

    static function getDetailList($list, $shopName = '') {
        $message = $shopName ? '商户:' . $shopName . '
' : '';
        foreach ($list['items'] as $menu) {
            $message .= self::generateFormat($menu) . '
';
        }
        return $message;
    }

//可以通过操作$t1,$t2修改位置，其值为间距值
    static function generateFormat($data) {
        $message = ($data['goods_number'] ? '[' . $data['goods_number'] . ']' : '') . $data['goods_name'] . $data['goods_spec'] . '
            ';
        $t1 = 1;
        $t2 = 18 - self::getlength($data['goods_price']) - self::getlength($data['goods_counts']);
        for ($j = 0; $j < $t1; $j++) {
            $message .=' ';
        }
        $message .=$data['goods_price'];
        for ($j = 0; $j < $t2; $j++) {
            $message .=' ';
        }
        return $message . $data['goods_counts'];
    }

//生成位长度
    static function getlength($p1) {
        $t1 = 0;
        $encode = 'utf-8';
        for ($i = 0; $i < mb_strlen($p1, $encode); $i++) {
            //包含中文处理
            if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", mb_substr($p1, $i, 1, $encode))) {
                $t1 = $t1 + 2;
            } else {
                $t1 = $t1 + 1;
            }
        }
        return $t1;
    }

    static private function generateSign($msg) {
        return md5($msg['memberCode'] . $msg['msgDetail'] . $msg['deviceNo'] . $msg['reqTime'] . self::$setting['apiKey']);
    }

    /*
     * 获取返回消息
     */

    static public function getResultMsg($no = 0) {
        $arr = array('0' => 1, '-1' => 'IP地址不允许', '-2' => '关键参数为空或请求方式不对',
            '-3' => '客户编码不对', '-4' => '安全校验码不正确', '-5' => '请求时间失效', '-6' => '订单内容格式不对',
            '-7' => 'msgNo 的值重复', '-8' => '消息模式不对', '-9' => '服务器错误', '-10' => '服务器内部错误',
            '-111' => '打印终端不属于该账户');
        return isset($arr[$no]) ? $arr[$no] : $no;
    }

    static public function getDeviceStatus() {
        $now = TIME * 1000;
        $content = getHttp('http://my.feyin.net/api/listDevice?memberCode=' .
                self::$setting['mKey'] . '&reqTime=' . $now . '&securityCode=' .
                md5(self::$setting['mKey'] . $now . self::$setting['apiKey']));
        if (!$content) { //请求失败
            return false;
        } else {
            $sxe = new SimpleXMLElement($content);
            $data = array();
            foreach ($sxe->device as $device) {
                $data[] = array(
                    'id' => (string) $device['id'],
                    'status' => (string) $device->deviceStatus,
                    'paper' => (string) $device->paperStatus
                );
            }
            return $data;
        }
    }

}
